<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use App\Models\BackstageModel;
use App\Models\CommonModel;
use App\Models\UserModel;
use Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;

// require_once '../app/libary/captcha/Code.class.php';

class UserController extends BCommonController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/backstage/user/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('guest', ['except' => 'logout']);
    // }

    public function index(){
        // $field = ['id', 'nickname','user_name','user_phone','user_email','real_name','sex','reg_time'];
        $field = ['id', 'nickname','user_name','user_phone','user_email','sex','reg_time','family','name'];
        if(isset($_GET['keywords'])){
            $keywords = trim($_GET['keywords']);
            $list = DB::table('user')->select($field)->where('nickname','like','%'.$keywords.'%')->orWhere('user_name','like','%'.$keywords.'%')->orderBy('id','desc')->paginate(15);
        }else{
            $list = DB::table('user')->select($field)->orderBy('id','desc')->paginate(15);
        }

        foreach ($list as $key => $vv) {

            $money = CommonModel::getField('user_money','account_money',['uid'=>$vv->id ]);
            if($money==0){
                $money = '0.00';
            }
            $list[$key]->money = $money;
        }
        // dd($list);
        return view('backstage/user/index',['list'=>$list]);
    }
    
    public function edit($id){
        $table = 'user';
        $data =['id'=>$id];
        $user = CommonModel::getOne($table,$data);
        $money = CommonModel::getField('user_money','account_money',['uid'=>$id ]);
        return view('backstage/user/edit',['money'=>$money,'user'=>$user]);
    }
    public function doedit(Request $request){
        if($request->isMethod('POST')){
            $data = $request->all();
            if(empty($data['user_phone']) || empty($data['user_email']) || empty($data['bank_name']) || empty($data['bank_num']) || empty($data['bank_owner']) || empty($data['bank_owner']) || empty($data['idcard'])){
                return json_encode(['status' => 0, 'message'=>'帶“*”號項不能為空']);
            }
            $id = $data['id'];
            if($data['user_pass'] !=''){
                $user['user_pass'] = md5(base64_encode($data['user_pass']));
            }
            $oldData = CommonModel::getOne('user',['id'=>$id]);
            $user['is_ban'] = $data['is_ban'];
            $user['is_freeze'] = $data['is_freeze'];
            if(!empty($data['user_pass']) && !empty($data['re_user_pass'] && $data['user_pass']==$data['re_user_pass'] && strlen($data['user_pass'])>=6)){
                $user['user_pass'] = md5($data['user_pass']);
            }
            $file = $request->file('idcard_img');
            // dd($file);
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('status' => 0,'message'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('status' => 0,'message'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;

                    $uploaddirs = '/uploads/user/'; //圖片路徑
                    $path = date("Y-m-d", time());  //獲取當前時間
                    $uploaddir = $uploaddirs . $path . '/';
                    $user['idcard_img'] = $uploaddir.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('user')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }else{
                        if( !empty(session('user')->idcard_img) || !file_exists(session('user')->idcard_img) ){
                            @unlink(public_path() . $oldData->idcard_img);
                        }
                    }
                }
            }
            $user['nickname'] = $data['nickname'];
            $user['family'] = $data['family'];
            $user['name'] = $data['name'];
            // $user['sex'] = $data['sex'];
            // $user['idcard_time'] = $data['idcard_time'];
            // $user['birthday'] = $data['birthday'];
            // $user['address'] = $data['address'];
            $user['user_phone'] = $data['user_phone'];
            $user['user_email'] = $data['user_email'];
            $user['bank_name'] = $data['bank_name'];
            $user['bank_num'] = $data['bank_num'];
            // $user['bank_address'] = $data['bank_address'];
            $user['bank_owner'] = $data['bank_owner'];
            $user['idcard'] = $data['idcard'];
            $cheInfo = ['is_ban'=>'是否註銷','is_freeze'=>'是否凍結','user_pass'=>'登錄密碼','idcard_img'=>'證件照片','nickname'=>'昵称','family'=>'姓氏','name'=>'名字','user_phone'=>'手机号码','user_email'=>'邮箱号码','bank_name'=>'持卡銀行名稱','bank_num'=>'銀行帳護號碼','bank_owner'=>'持有人姓名','idcard'=>'證件號碼'];
            $save = CommonModel::updateData('user',['id'=>$id],$user);
            if($save == true){
                $logContent='';
                foreach ($user as $key => $value) {
                    if($user[$key]!=$oldData->$key){
                        $logContent.="将".$cheInfo[$key]."由:<b style='color:red'>".$oldData->$key."</b>,修改为:<b style='color:red'>".$user[$key]."</b>。";
                    }
                }
                saveCommonLog($id, $logContent, 'user', session('admin')->real_name, session('admin')->id, 3);
                CommonModel::updateData('user',['id'=>$id],['up_time'=>time() ]);
                $arrJson = array('status' => 1, 'message'=>'修改成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'修改失敗');
            }
            return json_encode($arrJson);
        }
    }
    // 查看會員詳細信息
    public function show($id)
    {
        $table = 'user';
        $data =['id'=>$id];
        $user = UserModel::getOneUser($data);
        // dd($user);
        return view('backstage/common/user',['user'=>$user]);
    }
    


}
